package com.yykj.base.server.service.impl;

import com.yykj.base.client.dto.template.FormFieldDTO;
import com.yykj.base.server.converter.FormFieldDTOConverter;
import com.yykj.base.server.model.entity.form.template.CommonFormField;
import com.yykj.base.server.model.repository.form.template.CommonFormFieldRepository;
import com.yykj.base.server.service.FormFieldService;
import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.common.util.LocalObjectUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class FormFieldServiceImpl  implements FormFieldService {
    @Override
    public FormFieldDTO editFormField(FormFieldDTO dto) {
        if(StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getType())){
            throw new NormalException(ResultEnums.PARAM_ERROR);
        }
        CommonFormField firstByName = commonFormFieldRepository.findFirstByName(dto.getName());

        CommonFormField formField;
        if(dto.getId()!=null && dto.getId()>0){
            formField = commonFormFieldRepository.findById(dto.getId()).orElseThrow(()->new NormalException(ResultEnums.NOT_EXIST));
            if(firstByName!=null && !firstByName.getId().equals(formField.getId())){
                throw new NormalException(ResultEnums.FIELD_EXIST_ERROR);
            }
            LocalObjectUtil.copyNullValue(dto,formField);
        }else{
            formField = new CommonFormField();
            BeanUtils.copyProperties(dto,formField);
            if(firstByName!=null){
                formField.setId(firstByName.getId());
            }
        }
        formField = commonFormFieldRepository.save(formField);
        dto.setId(formField.getId());
        return dto;
    }

    @Override
    public void deleteFormField(Integer id) {
        commonFormFieldRepository.deleteById(id);
    }

    @Override
    public List<FormFieldDTO> commonFormFieldList() {
        List<CommonFormField> all = commonFormFieldRepository.findAll();
        return FormFieldDTOConverter.convert(all);
    }

    private CommonFormFieldRepository commonFormFieldRepository;

    @Autowired
    public void setFormFieldRepository(CommonFormFieldRepository commonFormFieldRepository) {
        this.commonFormFieldRepository = commonFormFieldRepository;
    }

}
